package com.bua.toothfactory;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.view.ViewGroup;
import android.widget.*;
import com.bua.adapter.GallaryAdpter;
import com.bua.control.HuodongPaint;
import com.bua.control.ImageLableButton;
import com.bua.control.MultipleCheckButton;
import com.bua.control.SingleCheckButton;
import com.bua.dao.DesignItem;
import com.bua.datafactory.DataFactory;
import com.bua.datafactory.DesignDetailDataFactory;
import com.bua.net.NetConfig;
import com.bua.net.NetConfig.HttpRequestId;
import com.bua.net.RequestTask;
import com.bua.net.ResponseReport;
import com.bua.net.Tool;
import com.bua.net.obj.CreateHodongOrderObject;
import com.bua.toothfactory.config.Config;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.util.Base64;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import org.json.JSONException;

public class HuodongOrderActivity extends Activity implements ResponseReport {


    private SingleCheckButton scbJGS = null;
    private TextView tvDesignId = null;
    private TextView tvCreateDate = null;

    private Button btnCreateDesignOrder;
    private MultipleCheckButton mcbXFLX;
    private EditText etXFLXCount;
    private MultipleCheckButton mcbZDCL;
    private SingleCheckButton scbYJXXZD;
    private SingleCheckButton scbFZTPJ;
    private EditText etFZTPJCount;
    private LinearLayout huodongPaint;
    private GridView gvHdimg;

    private String designId;
    private String orderId;
    private String[] flieList;

    HuodongPaint paint;
//    CheckBox.OnCheckedChangeListener listener = new CheckBox.OnCheckedChangeListener() {
//
//        @Override
//        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//            //To change body of implemented methods use File | Settings | File Templates.
//            String sTag= buttonView.getTag().toString();
//            int tag=   Integer.valueOf(sTag) ;
//            paint.setToothImage(tag);
//
//        }
//    };

    void addToothCheck(LinearLayout view, int tag) {
//        CheckBox toothBox = new CheckBox(this.getBaseContext());
//        toothBox.setTag(tag);
//        toothBox.setChecked(true);
//        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 20);
//        params.setMargins(0, 5, 0, 0);
//        toothBox.setLayoutParams(params);
//        toothBox.setTextColor(Color.BLACK);
//        String text = String.format("%1$d-%2$d", tag / 10, tag % 10);
//        toothBox.setText(text);
//        toothBox.setOnCheckedChangeListener(listener);
//        view.addView(toothBox);


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.huodong_activity_order);
        Intent intent = this.getIntent();
        orderId = intent.getStringExtra("orderId");
        tvDesignId = (TextView) findViewById(R.id.tvDesignId);
        scbJGS = (SingleCheckButton) findViewById(R.id.scbJGSSelector);
        scbJGS.items = Config.JGSList;
       // flieList=Tool.getFileList(this,"hd/imgs");
        tvCreateDate = (TextView) findViewById(R.id.tvCreateDate);

        btnCreateDesignOrder = (Button) findViewById(R.id.btnCreateDesignOrder);
        btnCreateDesignOrder.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                HuodongOrderActivity.this.CreateDesignOrder();
            }
        });


        mcbXFLX = (MultipleCheckButton) findViewById(R.id.mcbXFLX);
        mcbXFLX.SetItems(Config.loose_xiufuleixing);
        etXFLXCount = (EditText) findViewById(R.id.etXFLXCount);
        mcbZDCL = (MultipleCheckButton) findViewById(R.id.mcbZDCL);
        mcbZDCL.SetItems(Config.loose_xiufucailiao);
        scbYJXXZD = (SingleCheckButton) findViewById(R.id.scbYJXXZD);
        scbYJXXZD.SetItems(Config.rengongyajian);
        scbFZTPJ = (SingleCheckButton) findViewById(R.id.scbFZTPJ);
        scbFZTPJ.SetItems(Config.loose_fuzhuotipeijian);
        etFZTPJCount = (EditText) findViewById(R.id.etFZTPJCount);
        gvHdimg=(GridView) findViewById(R.id.gvHdimg);
        huodongPaint = (LinearLayout) findViewById(R.id.hdPaint);

        LinearLayout toothSiteArea1 = (LinearLayout) findViewById(R.id.tsa1);
        LinearLayout toothSiteArea2 = (LinearLayout) findViewById(R.id.tsa2);
        LinearLayout toothSiteArea3 = (LinearLayout) findViewById(R.id.tsa3);
        LinearLayout toothSiteArea4 = (LinearLayout) findViewById(R.id.tsa4);

        if (designId == null) {
            paint = new HuodongPaint(this);
            paint.act=this;
            huodongPaint.addView(paint, 1);
            final Button kahuan = (Button) findViewById(R.id.btnKahuan);
            final Button xiangpi = (Button) findViewById(R.id.btnXiangpi);
            final Button jituo = (Button) findViewById(R.id.btnJituo);
            kahuan.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    kahuan.setTextColor(Color.RED);
                    xiangpi.setTextColor(Color.BLACK);
                    jituo.setTextColor(Color.BLACK);
                    paint.setToothViewStyle(2);
                }
            });

            jituo.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    kahuan.setTextColor(Color.BLACK);
                    xiangpi.setTextColor(Color.BLACK);
                    jituo.setTextColor(Color.RED);
                    paint.setToothViewStyle(1);
                }
            });


            xiangpi.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    kahuan.setTextColor(Color.BLACK);
                    xiangpi.setTextColor(Color.RED);
                    jituo.setTextColor(Color.BLACK);
                    paint.setToothViewStyle(3);
                }
            });

//            addToothCheck(toothSiteArea1, 11);
//            addToothCheck(toothSiteArea1, 12);
//            addToothCheck(toothSiteArea1, 13);
//            addToothCheck(toothSiteArea1, 14);
//            addToothCheck(toothSiteArea1, 15);
//            addToothCheck(toothSiteArea1, 16);
//            addToothCheck(toothSiteArea1, 17);
//            addToothCheck(toothSiteArea1, 18);
//
//            addToothCheck(toothSiteArea2, 21);
//            addToothCheck(toothSiteArea2, 22);
//            addToothCheck(toothSiteArea2, 23);
//            addToothCheck(toothSiteArea2, 24);
//            addToothCheck(toothSiteArea2, 25);
//            addToothCheck(toothSiteArea2, 26);
//            addToothCheck(toothSiteArea2, 27);
//            addToothCheck(toothSiteArea2, 28);
//
//            addToothCheck(toothSiteArea3, 31);
//            addToothCheck(toothSiteArea3, 32);
//            addToothCheck(toothSiteArea3, 33);
//            addToothCheck(toothSiteArea3, 34);
//            addToothCheck(toothSiteArea3, 35);
//            addToothCheck(toothSiteArea3, 36);
//            addToothCheck(toothSiteArea3, 37);
//            addToothCheck(toothSiteArea3, 38);
//
//            addToothCheck(toothSiteArea4, 41);
//            addToothCheck(toothSiteArea4, 42);
//            addToothCheck(toothSiteArea4, 43);
//            addToothCheck(toothSiteArea4, 44);
//            addToothCheck(toothSiteArea4, 45);
//            addToothCheck(toothSiteArea4, 46);
//            addToothCheck(toothSiteArea4, 47);
//            addToothCheck(toothSiteArea4, 48);

        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_design, menu);
        return true;
    }

    private void CreateDesignOrder() {
        CreateHodongOrderObject OrderObject = new CreateHodongOrderObject();
        OrderObject.xiufuleixing = mcbXFLX.GetTitle();
        OrderObject.xiufuCount = etXFLXCount.getText().toString();
        OrderObject.zhidingcailiao = mcbZDCL.GetTitle();
        OrderObject.yajianxiangxizhiding = scbYJXXZD.GetTitle();
        OrderObject.fuzhuotipeijian = scbFZTPJ.GetTitle();
        OrderObject.fuzhuotipeijianCount = etFZTPJCount.getText().toString();
        String Image = null;
        huodongPaint.setBackgroundColor(Color.WHITE);
        huodongPaint.setDrawingCacheEnabled(true);
        Bitmap bmPicture = huodongPaint.getDrawingCache();
        Bitmap mBitmap = Bitmap.createBitmap(bmPicture, 50, 0, 420, 600);
        ByteArrayOutputStream pictureOutput = new ByteArrayOutputStream();
        if (mBitmap != null && mBitmap.compress(CompressFormat.JPEG, 50, pictureOutput))
            Image = Base64.encodeToString(pictureOutput.toByteArray(),
                    Base64.DEFAULT);

        String JGSId = scbJGS.GetTitle().split(" ")[0];
        if(JGSId==null || JGSId.length()<=0)
        {
            Tool.showToast(this, "请输入完整信息");
            return;
        }
        String url = NetConfig.creatUrl(HttpRequestId.CREATE_DESIGN_ORDER);
        RequestTask request = new RequestTask();
        HashMap<String, String> requestData = NetConfig.CreateDesignOrder(orderId, "HD", JGSId, Image, OrderObject.CreateOrderObject());
        request.CreateTask(url, requestData, NetConfig.HttpRequestId.CREATE_DESIGN_ORDER.ordinal(), this);

    }

    @Override
    public void callBack(String result, int requestId) {
        //To change body of implemented methods use File | Settings | File Templates.
        NetConfig.HttpRequestId RequestId = NetConfig.HttpRequestId.values()[requestId];
        switch (RequestId) {
            case CREATE_DESIGN_ORDER: {
                DataFactory resultData=new DataFactory(result);
                if(resultData.status==200)
                {
                    try {
                        tvDesignId.setText("设计定单编号：" +resultData.body.getString("designID"));
//                        tvCreateDate.setText(resultData.body.getString("created"));
                        this.finish();
                    }   catch (JSONException e)
                    {

                    }

                }
            }
            break;
            case GET_DESIGN_ORDER_DETAIL: {
                SetDesignOrder(result);
            }
            break;
            default:
                break;
        }
    }

    private void SetDesignOrder(String jsonString) {
        DesignDetailDataFactory obj = new DesignDetailDataFactory(jsonString);
        tvCreateDate.setText("创建日期：" + obj.createdDate);
        tvDesignId.setText("设计单编号：" + obj.designId);
        scbJGS.setText(obj.jigongsuo);
        btnCreateDesignOrder.setVisibility(View.INVISIBLE);
        mcbXFLX.setText(obj.GetItem("修复类型").toString());
        mcbXFLX.setEnabled(false);
        etXFLXCount.setText(obj.GetItem("共计(件)").toString());
        etXFLXCount.setEnabled(false);
        mcbZDCL.setText(obj.GetItem("指定材料").toString());
        mcbZDCL.setEnabled(false);
        scbYJXXZD.setText(obj.GetItem("牙尖详细指定").toString());
        scbYJXXZD.setEnabled(false);
        scbFZTPJ.setText(obj.GetItem("附着体配件").toString());
        scbFZTPJ.setEnabled(false);

        etFZTPJCount.setText(obj.GetItem("共计(套)").toString());
        etFZTPJCount.setEnabled(false);
        ImageView image = new ImageView(this);
        image.setImageBitmap(BitmapFactory.decodeByteArray(obj.designImage, 0, obj.designImage.length));
        huodongPaint.addView(image);
    }

    public void setAdapter( int tag)
    {
        ArrayList<String> imgList = new ArrayList<String>();
        String[] Images=Tool.getFileList(this,"hd/"+tag) ;
        gvHdimg.setAdapter(new HDAdapter(this,Images,tag));
    }

    public class HDAdapter extends BaseAdapter {
        public Context mContext;
        int Tooth;
        String[] toothImage;
        public HDAdapter(Context context,
                         String[] ToothImage,int tooth) {
            super();
            mContext = context;
            toothImage =ToothImage;
            Tooth= tooth;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
//			if (OrderId == null)
//				return 0;
            if (toothImage == null)
                return 0;
            return toothImage.length;
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public View getView(final int arg0, View arg1, ViewGroup arg2) {
            // TODO Auto-generated method stub


            ImageLableButton ilbDesign = new ImageLableButton(mContext);
            ilbDesign.setBackgroundColor(Color.WHITE);
            Bitmap bm= BitmapFactory.decodeStream(Tool.getFile(mContext,"hd/"+Tooth,toothImage[arg0])) ;
            // 获得图片的宽高
            int width = bm.getWidth();
            int height = bm.getHeight();
            // 设置想要的大小
            int newWidth = 50;
            int newHeight = 50;
            // 计算缩放比例
            float scaleWidth = ((float) newWidth) / width;
            float scaleHeight = ((float) newHeight) / height;
            // 取得想要缩放的matrix参数
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeight);
            // 得到新的图片
            Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
                    true);


            ilbDesign.setImage( newbm);
            ilbDesign.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO 自动生成的方法存根
                    HuodongOrderActivity.this.paint.DrawTooth(Tooth,HDAdapter.this.toothImage[arg0]); //HDAdapter.this.toothsList.get(arg0)
                }
            });
            return ilbDesign;
            }
        }


}
